package com.eian.boot.module.system.post.service;

import com.eian.boot.common.core.exception.ExceptionHelper;
import com.eian.boot.common.core.utils.BeanCopierUtils;
import com.eian.boot.module.system.associations.user.post.service.UserPostRelationService;
import com.eian.boot.module.system.post.mapper.SysPostMapper;
import com.eian.boot.module.system.post.model.dto.PostCreateRequest;
import com.eian.boot.module.system.post.model.dto.PostQueryRequest;
import com.eian.boot.module.system.post.model.dto.PostUpdateRequest;
import com.eian.boot.module.system.post.model.entity.SysPostEntity;
import com.eian.boot.module.system.post.model.vo.PostDetailVO;
import com.eian.boot.module.system.post.model.vo.PostSimpleVO;
import com.eian.boot.module.system.post.model.vo.PostVO;
import com.eian.boot.mybatis.core.page.PageResult;
import com.eian.boot.mybatis.core.service.BaseService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.eian.boot.common.constants.ErrorMessage.Post;
import static com.eian.boot.table.Tables.sys_post;

/**
 * 系统岗位服务
 *
 * @author alex.meng
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class SysPostService extends BaseService<SysPostMapper, SysPostEntity> {

    private final UserPostRelationService userPostRelationService;

    /**
     * 创建岗位
     */
    @Transactional(rollbackFor = Exception.class)
    public void createPost(PostCreateRequest request) {
        // 检查岗位编码是否重复
        boolean exists = this.queryChain()
                .where(sys_post.post_code.eq(request.getPostCode()))
                .exists();
        ExceptionHelper.ifTrue(exists, Post.CODE_EXIST);

        SysPostEntity post = BeanCopierUtils.copy(request, SysPostEntity.class);
        this.save(post);
    }

    /**
     * 分页查询岗位列表
     */
    public PageResult<PostVO> getPostList(PostQueryRequest request) {
        QueryWrapper query = QueryWrapper.create()
                .from(sys_post)
                .where(sys_post.post_code.eq(request.getPostCode(), StringUtils.isNotBlank(request.getPostCode())))
                .and(sys_post.post_name.like(request.getPostName(), StringUtils.isNotBlank(request.getPostName())))
                .and(sys_post.status.eq(request.getStatus(), request.getStatus() != null))
                .orderBy(sys_post.sort_order, true)
                .orderBy(sys_post.created_at, false);

        Page<SysPostEntity> page = this.page(request.buildPage(), query);
        List<PostVO> voList = BeanCopierUtils.copyList(page.getRecords(), PostVO.class);

        return new PageResult<>(voList, page.getTotalRow());
    }

    /**
     * 获取岗位详情
     */
    public PostDetailVO getPostDetail(Long id) {
        SysPostEntity post = this.getById(id);
        ExceptionHelper.ifNull(post, Post.NOT_EXIST);
        return BeanCopierUtils.copy(post, PostDetailVO.class);
    }

    /**
     * 更新岗位信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePost(PostUpdateRequest request) {
        SysPostEntity post = this.getById(request.getId());
        ExceptionHelper.ifNull(post, Post.NOT_EXIST);

        // 检查岗位编码是否重复
        if (StringUtils.isNotBlank(request.getPostCode()) && !request.getPostCode().equals(post.getPostCode())) {
            boolean exists = this.queryChain()
                    .where(sys_post.post_code.eq(request.getPostCode()))
                    .and(sys_post.id.ne(request.getId()))
                    .exists();
            ExceptionHelper.ifTrue(exists, Post.CODE_EXIST);
        }

        // 更新岗位信息
        BeanCopierUtils.copy(request, post);
        this.updateById(post);
    }

    /**
     * 删除岗位
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePost(Long id) {
        SysPostEntity post = this.getById(id);
        ExceptionHelper.ifNull(post, Post.NOT_EXIST);

        // 检查是否有用户关联
        long userCount = userPostRelationService.countUsersByPostId(id);
        ExceptionHelper.ifTrue(userCount > 0, Post.HAS_USER_BIND);

        this.removeById(id);

        // 级联删除岗位用户关系（保险操作）
        userPostRelationService.cascadeDeleteByPostId(id);
    }

    /**
     * 更新岗位状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePostStatus(Long id, Integer status) {
        SysPostEntity post = this.getById(id);
        ExceptionHelper.ifNull(post, Post.NOT_EXIST);

        post.setStatus(status);
        this.updateById(post);
    }

    /**
     * 获取所有岗位简单列表（用于下拉选择）
     */
    public List<PostSimpleVO> getAllSimplePosts() {
        List<SysPostEntity> posts = this.queryChain()
                .where(sys_post.status.eq(1))
                .orderBy(sys_post.sort_order, true)
                .list();
        return BeanCopierUtils.copyList(posts, PostSimpleVO.class);
    }

    /**
     * 根据用户ID查询岗位列表
     */
    public List<PostSimpleVO> getUserPosts(Long userId) {
        List<Long> postIds = userPostRelationService.getPostIdsByUserId(userId);

        if (postIds.isEmpty()) {
            return List.of();
        }

        List<SysPostEntity> posts = this.queryChain()
                .where(sys_post.id.in(postIds))
                .orderBy(sys_post.sort_order, true)
                .list();

        return BeanCopierUtils.copyList(posts, PostSimpleVO.class);
    }
}

